package com.trkj.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.EmpDAO;
import com.trkj.dao.EmployDAO;
import com.trkj.dao.LeaveDAO;
import com.trkj.dao.LoanDAO;
import com.trkj.dao.NoticeDAO;
import com.trkj.dao.OverworkDAO;
import com.trkj.dao.QuitDAO;
import com.trkj.dao.ReloanDAO;
import com.trkj.dao.StandardDAO;
import com.trkj.dao.TransferDAO;
import com.trkj.pojo.Employ;
import com.trkj.pojo.Leave;
import com.trkj.pojo.Loan;
import com.trkj.pojo.Notice;
import com.trkj.pojo.Overwork;
import com.trkj.pojo.Quit;
import com.trkj.pojo.Reloan;
import com.trkj.pojo.Standard;
import com.trkj.pojo.Transfer;
import com.trkj.vo.MyProcessesVo;

@Service
@Transactional
public class MyRequestService {
	@Autowired
	RepositoryService repositoryService;
	@Autowired
	HistoryService historyService;
	@Autowired
	RuntimeService runtimeService;
	@Autowired
	TaskService taskService;
	@Autowired
	WorkFlowService workFlowService;
	@Autowired
	EmpDAO empDAO;
	// 人员录用流程-------录用申请单
	@Autowired
	EmployDAO employDAO;
	// 人员转正流程-------转正申请单
	@Autowired
	StandardDAO standardDAO;
	// 人员借款流程-------借款申请单
	@Autowired
	LoanDAO loanDAO;
	// 人员请假流程-------请假申请单
	@Autowired
	LeaveDAO leaveDAO;
	// 人员调动流程-------调动申请单
	@Autowired
	TransferDAO transferDAO;
	// 人员还款流程-------还款申请单
	@Autowired
	ReloanDAO reloanDAO;
	// 人员加班流程-------加班申请单
	@Autowired
	OverworkDAO overworkDAO;
	// 人员离职流程-------离职申请单
	@Autowired
	QuitDAO quitDAO;
	// 通知发布流程-------通知申请单
	@Autowired
	NoticeDAO noticeDAO;
	/**
	 * 通过条件过滤集合
	 * @param processID 条件：流程id
	 * @param processState 条件：流程状态
	 * @param processName 条件：流程类别名称
	 * @param list 过滤的集合
	 * @return
	 */
	public List<MyProcessesVo> filterMyProcesses(String processID, String processState, String processName,
			List<MyProcessesVo> list) {
		List<MyProcessesVo> newlist = new ArrayList<>();
		if (list != null) {
			for (MyProcessesVo myProcessesVo : list) {
				if (processID != null && processID.length() > 0 && processName != null && processName.length() > 0
						&& processState != null && processState.length() > 0) {
					if (myProcessesVo.getMy_processID().indexOf(processID) >= 0 && myProcessesVo.getMy_processName().equals(processName)
							&& myProcessesVo.getMy_processState().equals(processState)) {
						newlist.add(myProcessesVo);
					}
					// processID 和 processName 不为空
				} else if (processID != null && processID.length() > 0 && processName != null && processName.length() > 0) {
					if (myProcessesVo.getMy_processID().indexOf(processID) >= 0 && myProcessesVo.getMy_processName().equals(processName)) {
						newlist.add(myProcessesVo);
					}
					// processID 和 processState 不为空
				} else if (processID != null && processID.length() > 0 && processState != null && processState.length() > 0) {
					if (myProcessesVo.getMy_processID().indexOf(processID) >= 0 && myProcessesVo.getMy_processState().equals(processState)) {
						newlist.add(myProcessesVo);
					}
					// processName 和  processState 不为空
				} else if (processName != null && processName.length() > 0 && processState != null && processState.length() > 0) {
					if (myProcessesVo.getMy_processName().equals(processName) && myProcessesVo.getMy_processState().equals(processState)) {
						newlist.add(myProcessesVo);
					}
					// processName 不为空
				} else if (processName != null && processName.length() > 0) {
					if (myProcessesVo.getMy_processName().equals(processName)) {
						newlist.add(myProcessesVo);
					}
					// processID 不为空
				} else if (processID != null && processID.length() > 0) {
					if (myProcessesVo.getMy_processID().indexOf(processID) >= 0) {
						newlist.add(myProcessesVo);
					}
					// processState 不为空
				} else if (processState != null && processState.length() > 0) {
					if (myProcessesVo.getMy_processState().equals(processState)) {
						newlist.add(myProcessesVo);
					}
				} else {
					newlist.add(myProcessesVo);
				}
			}
		}
		return newlist;
	}
	/**
	 * 将过滤的集合封装到jsp需要的map中并分页
	 * @param useid 
	 * @param processID
	 * @param processState
	 * @param processName
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String, Object> getPageMyRequest(Integer useid, String processID, String processState, String processName, Integer page,
			Integer rows) {
		Map<String, Object> map = new HashMap<>();
		if (page != null && page > 0 && rows != null && rows > 0) {
			List<MyProcessesVo> my_processes = find_my_processes(useid);
			List<MyProcessesVo> list = filterMyProcesses(processID, processState, processName, my_processes);
			List<MyProcessesVo> list2 = new ArrayList<>();
			Collections.sort(list);
			int i = (page - 1) * rows;// 起始下标
			int a = (page - 1) * rows;// 游动下标
			while (a - i < rows) {// 控制循环次数，固定为rows次
				if (a <= list.size() - 1) {// 防止最后一页时数组越界
					list2.add(list.get(a));// 在集合中加入当前页的数据
					a++;// 游动下标自加
				} else {
					break;// 最后一页，下标将越界时，退出循环
				}
			}
			map.put("total", list.size());
			map.put("rows", list2);
		}
		return map;
	}

	/**
	 * 查询登录人的全部流程（包括已经提交和未提交的）
	 * 
	 * @param userid
	 * @return
	 */
	public List<MyProcessesVo> find_my_processes(Integer useid) {
		List<MyProcessesVo> list = new ArrayList<>();
		List<Employ> employs = employDAO.findByLunchPeople(useid);
		for (Employ employ : employs) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员录用流程", employ.getEmployId());
			list.add(myProcessesVo);
		}
		List<Standard> standards = standardDAO.findByLunchPeople(useid);
		for (Standard standard : standards) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员转正流程", standard.getStandardId());
			list.add(myProcessesVo);
		}
		List<Loan> loans = loanDAO.findByLunchPeople(useid);
		for (Loan loan : loans) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员借款流程", loan.getLoanId());
			list.add(myProcessesVo);
		}
		List<Leave> leaves = leaveDAO.findByLunchPeople(useid);
		for (Leave leave : leaves) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员请假流程", leave.getLeaveId());
			list.add(myProcessesVo);
		}
		List<Transfer> transfers = transferDAO.findByLunchPeople(useid);
		for (Transfer transfer : transfers) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员调动流程", transfer.getTransferId());
			list.add(myProcessesVo);
		}
		List<Reloan> reloans = reloanDAO.findByLunchPeople(useid);
		for (Reloan reloan : reloans) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员还款流程", reloan.getReloanId());
			list.add(myProcessesVo);
		}
		List<Overwork> overworks = overworkDAO.findByLunchPeople(useid);
		for (Overwork overwork : overworks) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员加班流程", overwork.getOverworkId());
			list.add(myProcessesVo);
		}
		List<Quit> quits = quitDAO.findByLunchPeople(useid);
		for (Quit quit : quits) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("人员离职流程", quit.getQuitId());
			list.add(myProcessesVo);
		}
		List<Notice> notices = noticeDAO.findByLunchPeople(useid);
		for (Notice notice : notices) {
			MyProcessesVo myProcessesVo = getMyProcessesVo("通知发布流程", notice.getNoticeId());
			list.add(myProcessesVo);
		}
		return list;
	}

	/**
	 * 根据流程编号查询流程信息转成MyProcessesVo
	 * 
	 * @author Lixd
	 * @param processName
	 *            流程名称
	 * @param processid
	 *            流程编号
	 * @return
	 */
	private MyProcessesVo getMyProcessesVo(String processName, Integer processid) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		MyProcessesVo myProcessesVo = new MyProcessesVo();
		List<HistoricVariableInstance> variableInstances = historyService.createHistoricVariableInstanceQuery()
				.variableValueEquals("processid", processid).list();
		HistoricVariableInstance variableInstance = null;
		for (HistoricVariableInstance hiv : variableInstances) {
			String deploymentName = workFlowService.getProcessNameByProcessInstenceId(hiv.getProcessInstanceId());
			if (deploymentName.equals(processName)) {
				variableInstance = hiv;
				break;
			}
		}
		if (variableInstance != null) {
			String processInstanceId = variableInstance.getProcessInstanceId();
			HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery()
					.processInstanceId(processInstanceId).singleResult();
			// 设置我的申请信息
			myProcessesVo.setMy_processStartTime(sf.format(hpi.getStartTime()));
			if (hpi.getEndTime() != null) {
				myProcessesVo.setMy_processEndTime(sf.format(hpi.getEndTime()));
				myProcessesVo.setMy_taskName("结束");
				List<HistoricTaskInstance> tasklist = historyService.createHistoricTaskInstanceQuery().processInstanceId(hpi.getId()).list();
				myProcessesVo.setMy_taskId(tasklist.get(0).getId());
			} else {
				myProcessesVo.setMy_processEndTime("");
				Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
				myProcessesVo.setMy_taskName(task.getName());
				myProcessesVo.setMy_taskId(task.getId());
			}
			myProcessesVo.setMy_processState(hpi.getEndTime() != null ? "已完成" : "进行中");
		} else {
			myProcessesVo.setMy_processState("未开始");
			myProcessesVo.setMy_taskName("");
			myProcessesVo.setMy_taskId("0");
		}
		myProcessesVo.setMy_processID(processid + "");
		myProcessesVo.setMy_processName(processName);
		return myProcessesVo;
	}
	public boolean deleteProcess(Integer processId, String processName) {
		try {
			if (processName.equals("人员录用流程")) {
				employDAO.delete(processId);
			}else if (processName.equals("人员转正流程")) {
				standardDAO.delete(processId);
			} else if (processName.equals("人员借款流程")) {
				loanDAO.delete(processId);
			} else if (processName.equals("人员请假流程")) {
				leaveDAO.delete(processId);
			} else if (processName.equals("人员调动流程")) {
				transferDAO.delete(processId);
			} else if (processName.equals("人员还款流程")) {
				reloanDAO.delete(processId);
			} else if (processName.equals("人员加班流程")) {
				overworkDAO.delete(processId);
			} else if (processName.equals("人员离职流程")) {
				quitDAO.delete(processId);
			} else if (processName.equals("通知发布流程")) {
				noticeDAO.delete(processId);
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
